<template>
  <div class="bill-management-page">
    <!-- 1. 固定的搜索筛选区域 -->
    <div class="query-section">
      <el-card shadow="never" class="query-card">
        <el-form :model="queryParams" ref="queryFormRef" class="query-form" label-width="80px">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="老人姓名" prop="elderly_name">
                <el-input
                  v-model.trim="queryParams.elderly_name"
                  placeholder="请输入姓名或ID"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="账单月份" prop="bill_month">
                <el-date-picker
                  v-model="queryParams.bill_month"
                  type="month"
                  placeholder="请选择月份"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                  clearable
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label="支付状态" prop="status">
                <el-select
                  v-model="queryParams.status"
                  placeholder="请选择状态"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="全部" value="" />
                  <el-option label="未支付" value="unpaid" />
                  <el-option label="已支付" value="paid" />
                  <el-option label="已逾期" value="overdue" />
                  <el-option label="已作废" value="void" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <el-form-item label-width="0" class="action-buttons-wrapper">
                <el-button type="primary" :icon="Search" @click="handleQuery" :loading="loading">
                  查询
                </el-button>
                <el-button :icon="Refresh" @click="resetQuery">
                  重置
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>

    <!-- 2. 固定的操作栏 -->
    <div class="action-section">
      <el-card shadow="never" class="action-card">
        <div class="action-bar">
          <div class="action-left">
            <el-button :icon="Download" @click="handleExport" :disabled="!billList.length || loading">
              导出
            </el-button>
          </div>
          <div class="total-info">
            共 <strong class="total-count">{{ total }}</strong> 条记录
          </div>
        </div>
      </el-card>
    </div>

    <!-- 3. 可滚动的内容区域 -->
    <div class="content-section" ref="contentSectionRef">
      <el-card shadow="never" class="content-card">
        <!-- 桌面端表格 -->
        <div v-if="isDesktop" class="desktop-table">
          <el-table
            :data="billList"
            v-loading="loading || printing"
            element-loading-text="正在处理..."
            stripe
            border
            :header-cell-style="{ background: '#f8f9fa', color: '#606266' }"
            style="width: 100%; max-width: 1280px;">
            <el-table-column prop="billId" label="账单ID" align="center" fixed="left" width="100" />
            <el-table-column prop="elderlyName" label="老人姓名" fixed="left" width="140" show-overflow-tooltip />
            <el-table-column prop="billMonth" label="账单月份" align="center" width="140" />
            <el-table-column prop="totalAmount" label="总金额 (元)" align="right" width="150">
              <template #default="{ row }">
                <span class="amount-text">¥ {{ parseFloat(row.totalAmount).toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="支付状态" align="center" width="145">
              <template #default="{ row }">
                <el-tag :type="statusTagType(row.status)" effect="light">
                  {{ row.statusDesc || statusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="dueDate" label="截止日期" align="center" width="125" />
            <el-table-column
              v-if="containerWidth > 992"
              prop="paidAt"
              label="支付时间"
              align="center"
              width="160"
            >
              <template #default="{ row }">
                <span v-if="row.paidAt">{{ row.paidAt }}</span>
                <span v-else class="text-muted">-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="320">
              <template #default="{ row }">
                <div class="table-actions">
                  <el-button text type="primary" size="small" :icon="View" @click="handleViewDetails(row)">详情</el-button>
                  <el-button v-if="['unpaid', 'overdue'].includes(row.status)" text type="warning" size="small" :icon="Bell" @click="handleSendReminder(row)">催缴</el-button>
                  <el-button text type="info" size="small" :icon="Printer" @click="handlePrint(row)" :loading="printing">打印</el-button>
                </div>
              </template>
            </el-table-column>
         </el-table>
        </div>

        <!-- 移动端卡片列表 -->
        <div v-else class="mobile-list" :style="{ height: mobileListHeight }">
          <el-empty v-if="!billList.length && !loading" description="未查询到相关账单" />
          <div v-for="item in billList" :key="item.billId" class="mobile-card">
            <div class="card-header">
              <div class="header-left">
                <span class="elderly-name">{{ item.elderlyName }}</span>
                <span class="bill-month">{{ item.billMonth }}</span>
              </div>
              <el-tag :type="statusTagType(item.status)" size="small" effect="light">{{ item.statusDesc || statusText(item.status) }}</el-tag>
            </div>
            <div class="card-body">
              <div class="info-row amount-row">
                <span class="info-label">总金额</span>
                <span class="info-value amount">¥ {{ parseFloat(item.totalAmount).toFixed(2) }}</span>
              </div>
              <div class="info-row">
                <span class="info-label">截止日期</span>
                <span class="info-value">{{ item.dueDate }}</span>
              </div>
              <div v-if="item.paidAt" class="info-row">
                <span class="info-label">支付时间</span>
                <span class="info-value">{{ item.paidAt }}</span>
              </div>
            </div>
            <div class="card-actions">
              <el-button text type="primary" size="small" @click="handleViewDetails(item)" :icon="View">详情</el-button>
              <el-button v-if="['unpaid', 'overdue'].includes(item.status)" text type="warning" size="small" @click="handleSendReminder(item)" :icon="Bell">催缴</el-button>
              <el-button text type="info" size="small" @click="handlePrint(item)" :icon="Printer" :loading="printing">打印</el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 4. 固定的分页栏 -->
    <div class="pagination-section">
      <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        :layout="isDesktop ? 'total, sizes, prev, pager, next, jumper' : 'total, prev, next'"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination-container"
        background
      />
    </div>

    <!-- 查看详情的抽屉 (只读) -->
    <el-drawer v-model="detailsDrawerVisible" title="账单详情" direction="rtl" :size="isDesktop ? '50%' : '95%'" :before-close="handleDrawerClose">
      <div v-if="currentBill" class="drawer-content" v-loading="detailsLoading" element-loading-text="正在加载费用明细...">
        <el-alert title="此为历史账单快照，不可在此编辑。" type="info" show-icon :closable="false" class="drawer-alert" />
        <el-descriptions :column="isDesktop ? 2 : 1" border class="bill-descriptions">
          <el-descriptions-item label="账单ID">{{ currentBill.billId }}</el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="statusTagType(currentBill.status)">{{ currentBill.statusDesc || statusText(currentBill.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="老人姓名">{{ currentBill.elderlyName }}</el-descriptions-item>
          <el-descriptions-item label="账单月份">{{ currentBill.billMonth }}</el-descriptions-item>
          <el-descriptions-item label="总金额">
            <strong class="amount-highlight">¥ {{ parseFloat(currentBill.totalAmount).toFixed(2) }}</strong>
          </el-descriptions-item>
          <el-descriptions-item label="截止日期">{{ currentBill.dueDate }}</el-descriptions-item>
          <el-descriptions-item v-if="currentBill.paidAt" label="支付时间" :span="2">{{ currentBill.paidAt }}</el-descriptions-item>
        </el-descriptions>
        <h4 class="drawer-sub-title">费用明细</h4>
        <el-table :data="currentBill.details" border size="small" :summary-method="getSummaries" show-summary class="details-table">
          <el-table-column prop="itemDescription" label="费用描述" show-overflow-tooltip />
          <el-table-column prop="amount" label="金额 (元)" align="right" width="120">
            <template #default="{ row }">
              <span class="amount-text">¥ {{ parseFloat(row.amount).toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="detailsDrawerVisible = false">关闭</el-button>
          <el-button type="primary" :icon="Printer" @click="handlePrint(currentBill)" :loading="printing">打印此账单</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Download, View, Bell, Printer } from '@element-plus/icons-vue';
import { getBills, getBillById } from '@/api/bills';
// 【新增】导入 jsPDF 和 html2canvas
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

// --- State Management & Responsive Design ---
const screenWidth = ref(window.innerWidth);
const screenHeight = ref(window.innerHeight);
const isDesktop = computed(() => screenWidth.value >= 768);
const containerWidth = ref(0);
const contentSectionRef = ref(null);

const mobileListHeight = computed(() => {
  const topOffset = 290;
  const calculatedHeight = screenHeight.value - topOffset;
  return `${calculatedHeight > 200 ? calculatedHeight : 200}px`;
});

let resizeObserver = null;

onMounted(() => {
  window.addEventListener('resize', handleResize);
  fetchData();

  nextTick(() => {
    if (contentSectionRef.value && window.ResizeObserver) {
      resizeObserver = new ResizeObserver(entries => {
        if (entries[0]) {
          containerWidth.value = entries[0].contentRect.width;
        }
      });
      resizeObserver.observe(contentSectionRef.value);
    } else {
      handleResize();
    }
  });
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (resizeObserver) {
    resizeObserver.disconnect();
  }
});

const handleResize = () => {
  screenWidth.value = window.innerWidth;
  screenHeight.value = window.innerHeight;
  if (contentSectionRef.value) {
    containerWidth.value = contentSectionRef.value.offsetWidth;
  }
};

// --- State ---
const loading = ref(false);
const printing = ref(false); // 【新增】用于打印时的加载状态
const billList = ref([]);
const total = ref(0);
const queryFormRef = ref(null);

const createInitialQueryParams = () => ({
  page: 1,
  limit: 10,
  elderly_name: '',
  bill_month: '',
  status: '',
});

const queryParams = reactive(createInitialQueryParams());
const detailsDrawerVisible = ref(false);
const currentBill = ref(null);
const detailsLoading = ref(false);

// --- API & Core Methods ---
const fetchData = async () => {
  if (loading.value) return;
  loading.value = true;
  try {
    const apiParams = {
      current: queryParams.page,
      size: queryParams.limit,
      elderlyName: queryParams.elderly_name ? queryParams.elderly_name : null,
      billMonth: queryParams.bill_month ? queryParams.bill_month : null,
      status: queryParams.status ? queryParams.status : null
    };
    const pageData = await getBills(apiParams);
    if (pageData) {
      billList.value = pageData.records || [];
      total.value = Number(pageData.total || 0);
    } else {
      billList.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("Failed to fetch bill data:", error);
    billList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.page = 1;
  fetchData();
};

const resetQuery = () => {
  Object.assign(queryParams, createInitialQueryParams());
  nextTick(() => {
    queryFormRef.value?.resetFields();
    fetchData();
  });
};

const handleSizeChange = (newSize) => {
  queryParams.limit = newSize;
  handleQuery();
};

const handleCurrentChange = (newPage) => {
  queryParams.page = newPage;
  fetchData();
};

const handleViewDetails = async (row) => {
  detailsDrawerVisible.value = true;
  currentBill.value = { ...row, details: [] };
  detailsLoading.value = true;
  try {
    const detailsData = await getBillById(row.billId);
    if (detailsData && Array.isArray(detailsData)) {
      currentBill.value.details = detailsData;
    } else {
      currentBill.value.details = [];
      ElMessage.warning('未能获取到账单明细。');
    }
  } catch (error) {
    console.error(`Failed to fetch details for bill ID ${row.billId}:`, error);
    currentBill.value.details = [];
  } finally {
    detailsLoading.value = false;
  }
};

const handleDrawerClose = (done) => {
  currentBill.value = null;
  done();
};

const handleSendReminder = (row) => {
  ElMessageBox.confirm(`确定要向【${row.elderlyName}】的关联家属发送催缴提醒吗？`, '发送提醒', {
    confirmButtonText: '确定发送',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`已向【${row.elderlyName}】的关联家属发送 ${row.billMonth} 账单的催缴提醒。`);
  }).catch(() => { });
};

// --- Helper Functions ---
const statusTagType = (status) => ({ paid: 'success', unpaid: 'warning', overdue: 'danger', void: 'info' })[status] || 'primary';
const statusText = (status) => ({ paid: '已支付', unpaid: '未支付', overdue: '已逾期', void: '已作废' })[status] || '未知';

const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (column.property === 'amount') {
      const total = data.reduce((prev, curr) => {
        const value = Number(curr.amount);
        return !isNaN(value) ? prev + value : prev;
      }, 0);
      sums[index] = `¥ ${total.toFixed(2)}`;
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

// --- Export and Print Implementations ---

/**
 * 【新增】导出功能实现
 */
const handleExport = () => {
  ElMessage.info('正在生成CSV文件...');

  const headers = ['账单ID', '老人姓名', '账单月份', '总金额(元)', '支付状态', '截止日期', '支付时间'];
  const props = ['billId', 'elderlyName', 'billMonth', 'totalAmount', 'status', 'dueDate', 'paidAt'];

  // 处理特殊字符，防止CSV格式错乱
  const escapeCsvCell = (cell) => {
    if (cell === null || cell === undefined) {
      return '';
    }
    const str = String(cell);
    if (str.includes(',') || str.includes('"') || str.includes('\n')) {
      return `"${str.replace(/"/g, '""')}"`;
    }
    return str;
  };

  const csvContent = [
    headers.join(','),
    ...billList.value.map(row =>
      props.map(prop => {
        let value = row[prop];
        if (prop === 'status') {
          value = statusText(value);
        } else if (prop === 'totalAmount') {
          value = parseFloat(value).toFixed(2);
        }
        return escapeCsvCell(value);
      }).join(',')
    )
  ].join('\n');

  // 创建并下载文件
  const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', `账单列表_${new Date().toLocaleString()}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
  ElMessage.success('CSV文件已导出！');
};

/**
 * 【新增】打印功能实现
 * @param {object} row - The bill data object.
 */
const handlePrint = async (row) => {
  if (!row || printing.value) return;

  printing.value = true;
  ElMessage.info(`正在准备打印【${row.elderlyName}】的账单...`);

  // 1. 确保有完整的账单数据（包括明细）
  let fullBillData = { ...row };
  if (!row.details || row.details.length === 0) {
    try {
      const detailsData = await getBillById(row.billId);
      if (detailsData && Array.isArray(detailsData)) {
        fullBillData.details = detailsData;
      } else {
        fullBillData.details = [];
      }
    } catch (error) {
      ElMessage.error('获取账单明细失败，无法打印。');
      printing.value = false;
      return;
    }
  }

  // 2. 创建一个用于打印的隐藏DOM元素
  const printableElement = document.createElement('div');
  printableElement.id = 'printable-bill-content';
  printableElement.style.cssText = `
    position: absolute;
    left: -9999px;
    top: -9999px;
    width: 800px;
    padding: 40px;
    background: white;
    font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
  `;

  const detailsHtml = fullBillData.details.map(item => `
    <tr>
      <td>${item.itemDescription || ''}</td>
      <td style="text-align: right;">${parseFloat(item.amount).toFixed(2)}</td>
    </tr>
  `).join('');

  const totalAmount = parseFloat(fullBillData.totalAmount).toFixed(2);

  printableElement.innerHTML = `
    <style>
      #printable-bill-content * { box-sizing: border-box; }
      #printable-bill-content table { width: 100%; border-collapse: collapse; margin-top: 20px; }
      #printable-bill-content th, #printable-bill-content td { border: 1px solid #ccc; padding: 10px; font-size: 14px; }
      #printable-bill-content th { background-color: #f2f2f2; text-align: left; }
      #printable-bill-content h1 { text-align: center; margin-bottom: 20px; }
      #printable-bill-content .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 20px; }
      #printable-bill-content .info-item { display: flex; }
      #printable-bill-content .info-label { font-weight: bold; width: 100px; }
    </style>
    <h1>养老院费用账单</h1>
    <div class="info-grid">
      <div class="info-item"><span class="info-label">老人姓名:</span><span>${fullBillData.elderlyName}</span></div>
      <div class="info-item"><span class="info-label">账单月份:</span><span>${fullBillData.billMonth}</span></div>
      <div class="info-item"><span class="info-label">账单ID:</span><span>${fullBillData.billId}</span></div>
      <div class="info-item"><span class="info-label">支付状态:</span><span>${statusText(fullBillData.status)}</span></div>
      <div class="info-item"><span class="info-label">总金额:</span><span style="font-weight: bold; color: #d9534f;">¥ ${totalAmount}</span></div>
      <div class="info-item"><span class="info-label">截止日期:</span><span>${fullBillData.dueDate}</span></div>
    </div>
    <h3>费用明细</h3>
    <table>
      <thead>
        <tr>
          <th>费用描述</th>
          <th style="text-align: right;">金额 (元)</th>
        </tr>
      </thead>
      <tbody>
        ${detailsHtml}
        <tr>
          <th style="text-align: right;">合计</th>
          <th style="text-align: right;">¥ ${totalAmount}</th>
        </tr>
      </tbody>
    </table>
    <div style="text-align: right; margin-top: 30px; font-size: 12px;">打印日期: ${new Date().toLocaleDateString()}</div>
  `;
  document.body.appendChild(printableElement);

  // 3. 使用 html2canvas 和 jsPDF 生成 PDF
  try {
    const canvas = await html2canvas(printableElement, {
      scale: 2, // 提高清晰度
      useCORS: true,
    });

    const imgData = canvas.toDataURL('image/jpeg', 1.0);
    const pdf = new jsPDF('p', 'mm', 'a4');
    const pdfWidth = pdf.internal.pageSize.getWidth();
    const pdfHeight = pdf.internal.pageSize.getHeight();
    const imgWidth = canvas.width;
    const imgHeight = canvas.height;
    const ratio = imgWidth / imgHeight;

    let pageImgWidth = pdfWidth - 20; // 左右边距10mm
    let pageImgHeight = pageImgWidth / ratio;

    let position = 10; // 上边距10mm
    pdf.addImage(imgData, 'JPEG', 10, position, pageImgWidth, pageImgHeight);

    const fileName = `账单-${fullBillData.elderlyName}-${fullBillData.billMonth}.pdf`;
    pdf.save(fileName);
    ElMessage.success('PDF已生成！');

  } catch (err) {
    console.error('打印失败:', err);
    ElMessage.error('打印过程中发生错误。');
  } finally {
    // 4. 清理
    document.body.removeChild(printableElement);
    printing.value = false;
  }
};
</script>

<style lang="scss" scoped>
/* --- Layout --- */
.bill-management-page {
  width: 100%;
  height: 84vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  background-color: #f5f7fa;
}

.query-section,
.action-section,
.pagination-section {
  flex-shrink: 0;
}

.content-section {
  flex: 1;
  min-height: 0;
  position: relative;
}

.query-card, .action-card, .content-card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.06);
}

.content-card {
  height: 100%;
  display: flex;
  flex-direction: column;

  :deep(.el-card__body) {
    flex: 1;
    min-height: 0;
    overflow: hidden;
    padding: 20px;
  }
}

/* --- Query Form --- */
.query-form .action-buttons-wrapper {
  :deep(.el-form-item__content) {
    display: flex;
    gap: 10px;
  }
}

/* --- Action Bar --- */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}
.total-info {
  font-size: 14px;
  color: #606266;
  .total-count {
    color: var(--el-color-primary);
    font-size: 16px;
    font-weight: 600;
    margin: 0 4px;
  }
}

/* --- Tables & Lists --- */
.desktop-table,
.mobile-list {
  height: 100%;
  width: 100%;
}

.desktop-table {
  display: flex;
  justify-content: center; /* 水平居中 */
  .el-table {
    max-width: 1200px; /* 设置最大宽度，防止过宽 */
    width: 100%; /* 占满可用宽度，但不超过max-width */
  }
}

.mobile-list {
  overflow-y: auto;
}

.amount-text, .amount-highlight {
  font-weight: 600;
  color: #e65d5d;
}
.amount-highlight {
  font-size: 16px;
}
.text-muted {
  color: #a8abb2;
}

/* --- Mobile View --- */
.mobile-list .mobile-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease, transform 0.3s ease;
}
.mobile-list .mobile-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}
.mobile-list .card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f2f5;
  gap: 8px;
}
.mobile-list .card-header .header-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.mobile-list .card-header .elderly-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
.mobile-list .card-header .bill-month {
  font-size: 13px;
  color: #909399;
}
.mobile-list .card-body {
  padding: 12px 0;
}
.mobile-list .card-body .info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
}
.mobile-list .card-body .info-row .info-label { color: #606266; }
.mobile-list .card-body .info-row .info-value { color: #303133; font-weight: 500; }
.mobile-list .card-body .info-row.amount-row .info-value { font-size: 16px; }
.mobile-list .card-actions {
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* --- Pagination --- */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
}

/* --- Drawer --- */
.drawer-content {
  padding: 0 20px;
}
.drawer-content .drawer-alert { margin-bottom: 20px; }
.drawer-content .bill-descriptions { margin-bottom: 24px; }
.drawer-content .drawer-sub-title {
  margin: 24px 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
.drawer-footer {
  padding: 16px 20px;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* --- Responsive Adjustments --- */
@media (max-width: 767.98px) {
  .bill-management-page {
    padding: 8px;
    gap: 12px;
  }
  .content-card :deep(.el-card__body) {
    flex: 1;
    min-height: 0;
    overflow: hidden;
    padding: 20px;
    width: 100%;
  }
  .action-bar .action-left {
    flex-grow: 1;
    .el-button {
      width: 100%;
    }
  }
  .pagination-container {
    justify-content: center;
    :deep(.el-pagination__sizes) {
      display: none;
    }
  }
}
</style>